/*
 * This thread receives from Buffer and write down to SVG Server process.
 * This is the trace buffer.
 */
package client;

import common.Helper;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import serveursvg.IRmiServerSvgWriter;

/**
 *
 *
 */
public class SvgClientThread implements Runnable
{
    private IRmiServerSvgWriter rmiServerSvgWriter;
    private Buffer buffer;
    private boolean running;

    public SvgClientThread(Buffer buffer) throws RemoteException
    {
        this.buffer = buffer;
        this.running = true;
    }

    /**
     * Checks for remote objectavaibility and connects to it
     */
    private void connectToRmiServerSvgWriter()
    {
        // waits for remote object avaibility
        Helper.waitForRemoteObjectAvaibility(Helper.SVG_WRITER_RMI);

        // we can now connect to the server
        try
        {
            rmiServerSvgWriter = (IRmiServerSvgWriter) Naming.lookup(
                    "rmi://localhost:1099/" + Helper.SVG_WRITER_RMI);
        } catch (NotBoundException ex)
        {
            Logger.getLogger(SvgClientThread.class.getName()).log(
                    Level.SEVERE, null, ex);
        } catch (MalformedURLException ex)
        {
            Logger.getLogger(SvgClientThread.class.getName()).log(
                    Level.SEVERE, null, ex);
        } catch (RemoteException ex)
        {
            Logger.getLogger(SvgClientThread.class.getName()).log(
                    Level.SEVERE, null, ex);
        }
    }

    /**
     * gently stop the thread
     */
    public void stop()
    {
        running = false;
    }

    /**
     * Get the value of bufferMessage
     *
     * @return the value of bufferMessage
     */
    public Buffer getBuffer()
    {
        return buffer;
    }

    /**
     * Set the value of bufferMessage
     *
     * @param bufferMessage new value of bufferMessage
     */
    public void setBuffer(Buffer bufferMessage)
    {
        this.buffer = bufferMessage;
    }

    public void run()
    {
        BufferMessage bufferMessage;
        connectToRmiServerSvgWriter();

        // Reading 10 messages from the Buffer mailbox.
        while(running)
        {
            // Receiving the bufferMessage from the "mailbox-like" buffer.
            bufferMessage = buffer.get();
            try
            {
                rmiServerSvgWriter.exec(bufferMessage.getMessageType(),
                        bufferMessage.getParams());
            } catch (RemoteException ex)
            {
                Logger.getLogger(SvgClientThread.class.getName()).log(
                        Level.SEVERE, null, ex);
            }
        }
    }
}
